#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <mysql++.h>

using namespace std;
using namespace mysqlpp;

int load_level_words (map <string, int> & words_level_map, string words_path, int words_level)
{
	ifstream obj_file (words_path.c_str());
	if (!obj_file)
	{
		cout << __LINE__ << " level 1 words file load fail!" << endl;
		//throw an exception
		return -1;	//使用异常的时候删除
	}
	string str, strs, stred, str_ing;
	while ( obj_file >> str )
	{
		//即使此单词在底一级出现过，只要在高一级再次出现，就赋予此单词高一级的难度值
		//因此此处不用判断以前此单词是否出现过
		words_level_map[str] = words_level;
		//strs = str + "s";
		//words_level_map[strs] = words_level;
		//stred = str + "ed";
		//words_level_map[stred] = words_level;
		//str_ing = str + "ing";
		//words_level_map[str_ing] = words_level;
	}
	obj_file.close();
	return 0;
}

//从数据库里加载所有单词的所有变形
int load_spellchecker (map <string, int> & all_words)
{
	try
	{
		Connection conn("spellchecker", "127.0.0.1", "root", "aids00a");
		Query query(conn.query());
		string temp;
		string sql = "select * from sc_dictionary;";
		if (UseQueryResult res = query.use(sql))
		{
			while (Row row = res.fetch_row())
			{
				row["word"].to_string(temp);
				all_words[temp] = 0;
			}
		}
	}
	catch (const Exception& er)
	{
		cout << __LINE__ << er.what() << endl;
	}
	return 0;
}


/*
这个程序生成一个级别的单词的所有变形，比如动词的过去式，名词复数，变形规则完全符合英语的词法
然后把每一类变形储存在一个单独的文件里，并且使用result4.eing的格式命名，生成文件中的单词由PHP脚本负责存入数据库
根据英语词法规则修改一个单词的后缀，然后对新单词进行拼写检查，存在这个单词，就把这个新单词放入文件
程序的最大缺点是自动化程度低，没有分析单词变形之间的关系，存在大量的新单词而不是单词词尾变形所得单词，如for->forest，这个需要人力剔除
可以进行的检查有，如果一个词通过了ing和ed形式的拼写检查，那么它就不可能有ly形式的变形；一个词通过了er和est的拼写检查那它ed和ing形式的变形肯定是个新单词了。这样就可以节省人力了
*/
int main (int argc, char* argv[])
{
	map <string, int> level_words, all_words;
	string level, path;
	if (argc > 1)
	{
		level = *argv[1];
		path = "../words_levels/" + level + ".txt";
		load_level_words (level_words, path, 1);
	}
	else
	{
		cout << "参数不够！" << endl;
		return 0;
	}
	
	//load_level_words (level_words, "../words_levels/1.txt", 1);
	//load_level_words (level_words, "../words_levels/2.txt", 2);
	//load_level_words (level_words, "../words_levels/3.txt", 3);
	//load_level_words (level_words, "../words_levels/4.txt", 4);
	//load_level_words (level_words, "../words_levels/5.txt", 5);
	load_spellchecker (all_words);
	map<string, int>::iterator it, it_all;
	string temp_str;
	for ( it = level_words.begin() ; it != level_words.end(); it++ )
	{
		temp_str = it->first;
		//if (temp_str[temp_str.size()-1] == 'y')
		{
			
			//将最后一个字母截去
			//*- temp_str = temp_str.substr(0, temp_str.size()-1);
			//cout << temp_str << endl;

			it_all = all_words.find(it->first + "d");
			//拼写检查
			//it_all = all_words.find(temp_str + "ily");
			if (all_words.end() != it_all )
			{
				//cout << it->first + "est" << endl;
				cout << temp_str + "d" << endl;
			}
		}
	}
	return 0;
}

